package com.upbos.upm.common.logo;

import com.upbos.upm.cfg.CfgUtil;
import com.upbos.upm.entity.Cfg;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("upm")
public class LogoController {

    @GetMapping("public/img")
    public void img(HttpServletResponse response, String image) throws IOException {
        Cfg logoCfg = CfgUtil.getCfg("logo.dir");
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String path = logoCfg == null ? "" : logoCfg.getValue();
        Resource resource = resolver.getResource(path + "/" + image);
        if (!resource.exists()) {
            resource = resolver.getResource("classpath:static/upm/public/image/" + image);
        }
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        BufferedImage bi  = ImageIO.read(resource.getFile());

        ImageIO.write(bi, "jpg", out);
    }
}
